/*
 *************************************************************************
 * The contents of this file are subject to the Openbravo  Public  License
 * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
 * Version 1.1  with a permitted attribution clause; you may not  use this
 * file except in compliance with the License. You  may  obtain  a copy of
 * the License at http://www.openbravo.com/legal/license.html
 * Software distributed under the License  is  distributed  on  an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific  language  governing  rights  and  limitations
 * under the License.
 * The Original Code is Openbravo ERP.
 * The Initial Developer of the Original Code is Openbravo SLU
 * All portions are Copyright (C) 2001-2013 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  Cheli Pineda__________________________.
 ************************************************************************
 */
package org.openbravo.furniture.ad_actionButton;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openbravo.base.filter.IsIDFilter;
import org.openbravo.base.secureApp.HttpSecureAppServlet;
import org.openbravo.base.secureApp.VariablesSecureApp;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.erpCommon.reference.PInstanceProcessData;
import org.openbravo.erpCommon.utility.OBError;
import org.openbravo.erpCommon.utility.SequenceIdData;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.model.ad.process.ProcessInstance;
import org.openbravo.model.ad.ui.Process;
import org.openbravo.model.common.invoice.Invoice;
import org.openbravo.model.common.order.Order;
import org.openbravo.model.materialmgmt.transaction.ShipmentInOut;
import org.openbravo.service.db.CallProcess;
import org.openbravo.xmlEngine.XmlDocument;

public class CreateFromShipmentFurniturePO extends HttpSecureAppServlet {
  private static final long serialVersionUID = 1L;
  private static final BigDecimal ZERO = BigDecimal.ZERO;
  private static final String M_Inout_Post_ID = "109";
  private static final String M_Inout_Table_ID = "319";
  private static final String Goods_Document_Action = "135";
  private static final String Goods_Receipt_Window = "184";

  @Override
  public void init(ServletConfig config) {
    super.init(config);
    boolHist = false;
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException,
      ServletException {
    final VariablesSecureApp vars = new VariablesSecureApp(request);

    if (vars.commandIn("DEFAULT")) {

      final String strTableId = vars.getGlobalVariable("inpTableId", "CreateFrom|tableId", "");
      final String strProcessId = vars
          .getGlobalVariable("inpProcessId", "CreateFrom|processId", "");
      final String strPath = vars.getGlobalVariable("inpPath", "CreateFrom|path", strDireccion
          + request.getServletPath());
      final String strWindowId = vars.getGlobalVariable("inpWindowId", "CreateFrom|windowId", "");
      final String strKey = vars.getGlobalVariable("inpcOrderId", strWindowId + "|" + "C_Order_ID");
      final String strTabName = vars.getGlobalVariable("inpTabName", "CreateFrom|tabName", "");
      final String strBPartner = vars
          .getGlobalVariable("inpcBpartnerId", "CreateFrom|bpartner", "");

      // 26-06-07
      vars.setSessionValue("CreateFrom|default", "1");
      printPageShipment(response, vars, strPath, strKey, strTableId, strProcessId, strWindowId,
          strTabName, strBPartner);
      // printPage_FS(response, vars, strPath, strKey, strTableId, strProcessId, strWindowId,
      // strTabName, strDateInvoiced, strBPartnerLocation, strMPriceList, strBPartner,
      // strStatementDate, strBankAccount, strOrg, strIsreceipt);
    } else if (vars.commandIn("FIND_PO", "FIND_INVOICE", "FIND_SHIPMENT", "FIND_BANK",
        "FIND_SETTLEMENT")) {
      final String strKey = vars.getRequiredStringParameter("inpKey");
      final String strTableId = vars.getStringParameter("inpTableId");
      final String strProcessId = vars.getStringParameter("inpProcessId");
      final String strPath = vars.getStringParameter("inpPath",
          strDireccion + request.getServletPath());
      final String strWindowId = vars.getStringParameter("inpWindowId");
      final String strTabName = vars.getStringParameter("inpTabName");
      final String strBPartner = vars.getStringParameter("inpcBpartnerId");

      printPageShipment(response, vars, strPath, strKey, strTableId, strProcessId, strWindowId,
          strTabName, strBPartner);
    } else if (vars.commandIn("SAVE")) {
      final String strProcessId = vars.getStringParameter("inpProcessId");
      final String strKey = vars.getRequiredStringParameter("inpKey");
      final String strTableId = vars.getStringParameter("inpTableId");
      final String strWindowId = vars.getStringParameter("inpWindowId");

      // Set this special case for auditing
      SessionInfo.setProcessType("CF");
      SessionInfo.setProcessId(strTableId);

      final OBError myMessage = saveShipment(vars, strKey, strTableId, strProcessId, strWindowId);
      // final String strTabId = vars.getGlobalVariable("inpTabId", "CreateFrom|tabId", "");
      final String strTabId = "294";
      vars.setMessage(strTabId, myMessage);

      printPageClosePopUp(response, vars);
      vars.removeSessionValue("CreateFrom|key");
      vars.removeSessionValue("CreateFrom|processId");
      vars.removeSessionValue("CreateFrom|path");
      vars.removeSessionValue("CreateFrom|windowId");
      vars.removeSessionValue("CreateFrom|tabName");
      vars.removeSessionValue("CreateFrom|dateInvoiced");
      vars.removeSessionValue("CreateFrom|bpartnerLocation");
      vars.removeSessionValue("CreateFrom|pricelist");
      vars.removeSessionValue("CreateFrom|bpartner");
      vars.removeSessionValue("CreateFrom|statementDate");
      vars.removeSessionValue("CreateFrom|bankAccount");
      vars.removeSessionValue("CreateFrom|adOrgId");
      vars.removeSessionValue("CreateFrom|isreceipt");
      // response.sendRedirect(strPath);
    } else
      pageErrorPopUp(response);
  }

  protected void printPageShipment(HttpServletResponse response, VariablesSecureApp vars,
      String strPath, String strKey, String strTableId, String strProcessId, String strWindowId,
      String strTabName, String strBPartner) throws IOException, ServletException {
    if (log4j.isDebugEnabled())
      log4j.debug("Output: Shipment");
    CreateFromShipmentFurnitureData[] data = null;
    XmlDocument xmlDocument;
    // String strPO = vars.getStringParameter("inpPurchaseOrder");
    log4j.debug("00000000000000000000: " + strKey);
    String strPO = strKey;
    String strInvoice = vars.getStringParameter("inpInvoice");
    // ShipmentInOut shipment = OBDal.getInstance().get(ShipmentInOut.class, strKey);
    Order objOrder = OBDal.getInstance().get(Order.class, strKey);
    final String strLocator = vars.getStringParameter("inpmLocatorId");
    final String isSOTrx = Utility.getContext(this, vars, "isSOTrx", strWindowId);
    strInvoice = "";

    xmlDocument = xmlEngine.readXmlTemplate(
        "org/openbravo/furniture/ad_actionButton/CreateFromShipmentFurniturePO").createXmlDocument();

    log4j.debug("vars.getLanguage(): " + vars.getLanguage());
    log4j.debug("Utility.getContext(this, vars, User_Client, strWindowId): "
        + Utility.getContext(this, vars, "#User_Client", strWindowId));
    log4j.debug("Utility.getContext(this, vars, User_Org, strWindowId): "
        + Utility.getContext(this, vars, "#User_Org", strWindowId));
    log4j.debug("strPO: " + strPO);

  //  data = CreateFromShipmentFurnitureData.selectfurnitureshipment(this, vars.getLanguage(), strPO);
data = CreateFromShipmentFurnitureData.selectfurnitureshipmentPO(this, vars.getLanguage(), strPO);
    log4j.debug("dataaaaaaaaaaa: " + data.length);

    /*
     * if (strPO.equals("") && strInvoice.equals("")) { final String[] discard = { "sectionDetail"
     * }; if (isSOTrx.equals("Y")) xmlDocument = xmlEngine.readXmlTemplate(
     * "org/openbravo/furniture/ad_actionButton/CreateFromShipmentFurniture", discard)
     * .createXmlDocument(); else xmlDocument = xmlEngine.readXmlTemplate(
     * "org/openbravo/erpCommon/ad_actionButton/CreateFrom_ShipmentPO", discard)
     * .createXmlDocument(); data = CreateFromShipmentFurnitureData.set(); } else { if
     * (isSOTrx.equals("Y")) xmlDocument = xmlEngine.readXmlTemplate(
     * "org/openbravo/erpCommon/ad_actionButton/CreateFromShipmentFurniture") .createXmlDocument();
     * else xmlDocument = xmlEngine.readXmlTemplate(
     * "org/openbravo/erpCommon/ad_actionButton/CreateFrom_ShipmentPO").createXmlDocument(); if
     * (strInvoice.equals("")) { if (vars.getLanguage().equals("en_US")) { if (isSOTrx.equals("Y"))
     * { data = CreateFromShipmentFurnitureData.selectFromPOSOTrx(this, vars.getLanguage(),
     * Utility.getContext(this, vars, "#User_Client", strWindowId), Utility.getContext(this, vars,
     * "#User_Org", strWindowId), strPO); } else { data =
     * CreateFromShipmentFurnitureData.selectFromPO(this, vars.getLanguage(),
     * Utility.getContext(this, vars, "#User_Client", strWindowId), Utility.getContext(this, vars,
     * "#User_Org", strWindowId), strPO); } } else { if (isSOTrx.equals("Y")) data =
     * CreateFromShipmentFurnitureData.selectFromPOTrlSOTrx(this, vars.getLanguage(),
     * Utility.getContext(this, vars, "#User_Client", strWindowId), Utility.getContext(this, vars,
     * "#User_Org", strWindowId), strPO); else data =
     * CreateFromShipmentFurnitureData.selectFromPOTrl(this, vars.getLanguage(),
     * Utility.getContext(this, vars, "#User_Client", strWindowId), Utility.getContext(this, vars,
     * "#User_Org", strWindowId), strPO); } } else { if (vars.getLanguage().equals("en_US")) { if
     * (isSOTrx.equals("Y")) data = CreateFromShipmentFurnitureData.selectFromInvoiceTrx(this,
     * vars.getLanguage(), Utility.getContext(this, vars, "#User_Client", strWindowId),
     * Utility.getContext(this, vars, "#User_Org", strWindowId), strInvoice); else data =
     * CreateFromShipmentFurnitureData.selectFromInvoice(this, vars.getLanguage(),
     * Utility.getContext(this, vars, "#User_Client", strWindowId), Utility.getContext(this, vars,
     * "#User_Org", strWindowId), strInvoice); } else { if (isSOTrx.equals("Y")) data =
     * CreateFromShipmentFurnitureData.selectFromInvoiceTrx(this, vars.getLanguage(),
     * Utility.getContext(this, vars, "#User_Client", strWindowId), Utility.getContext(this, vars,
     * "#User_Org", strWindowId), strInvoice); else data =
     * CreateFromShipmentFurnitureData.selectFromInvoiceTrl(this, vars.getLanguage(),
     * Utility.getContext(this, vars, "#User_Client", strWindowId), Utility.getContext(this, vars,
     * "#User_Org", strWindowId), strInvoice); } } }
     */

    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    xmlDocument.setParameter("theme", vars.getTheme());
    xmlDocument.setParameter("path", strPath);
    xmlDocument.setParameter("key", strKey);
    xmlDocument.setParameter("tableId", strTableId);
    xmlDocument.setParameter("processId", strProcessId);
    xmlDocument.setParameter("cBpartnerId", strBPartner);
    xmlDocument.setParameter("BPartnerDescription",
        CreateFromShipmentFurnitureData.selectBPartner(this, strBPartner));
    xmlDocument.setParameter("PurchaseOrder", strPO);

    xmlDocument.setParameter("Invoice", strInvoice);
    xmlDocument.setParameter("pType", (!strInvoice.equals("") ? "INVOICE"
        : (!strPO.equals("")) ? "PO" : ""));
    xmlDocument.setParameter("windowId", strWindowId);
    xmlDocument.setParameter("tabName", strTabName);


    xmlDocument.setParameter("M_Locator_ID", strLocator);
    xmlDocument.setParameter("M_Locator_ID_DES",
        CreateFromShipmentFurnitureData.selectLocator(this, strLocator));


    {
      final OBError myMessage = vars.getMessage("CreateFromShipmentFurniturePO");
      vars.removeMessage("CreateFromShipmentFurniturePO");
      if (myMessage != null) {
        xmlDocument.setParameter("messageType", myMessage.getType());
        xmlDocument.setParameter("messageTitle", myMessage.getTitle());
        xmlDocument.setParameter("messageMessage", myMessage.getMessage());
      }
    }

    /*
     * if (isSOTrx.equals("N")) { final CreateFromShipmentFurnitureData[][] dataUOM = new
     * CreateFromShipmentFurnitureData[data.length][];
     * 
     * for (int i = 0; i < data.length; i++) { // Obtain the specific units for each product
     * 
     * dataUOM[i] = CreateFromShipmentFurnitureData.selectUOM(this, data[i].mProductId);
     * 
     * // Check the hidden fields
     * 
     * final String strhavesec = data[i].havesec;
     * 
     * if ("0".equals(strhavesec)) { data[i].havesec = "hidden"; data[i].havesecuom = "none"; } else
     * { data[i].havesec = "text"; data[i].havesecuom = "block"; } }
     * xmlDocument.setDataArray("reportM_Product_Uom_To_ID", "liststructure", dataUOM); }
     */
    xmlDocument.setData("structure1", data);
    response.setContentType("text/html; charset=UTF-8");
    final PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }

  void printPageInvoiceCombo(HttpServletResponse response, VariablesSecureApp vars,
      String strBPartner, String strWindowId, String strKey) throws IOException, ServletException {
    if (log4j.isDebugEnabled())
      log4j.debug("Output: Refresh Invoices");
    final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
        "org/openbravo/erpCommon/ad_actionButton/CreateFrom_F0").createXmlDocument();
    String strArray = "";
    String strArray2 = "";
    final String isSOTrx = Utility.getContext(this, vars, "isSOTrx", strWindowId);

    if (strBPartner.equals("")) {
      strArray = Utility.arrayEntradaSimple("arrDatos", new CreateFromShipmentFurnitureData[0]);
      strArray2 = Utility.arrayEntradaSimple("arrDatos2", new CreateFromShipmentFurnitureData[0]);
    } else {
      if (vars.commandIn("REFRESH_INVOICES")) { // Loading the combos in
        // the delivery note's
        // CreateFrom
        if (isSOTrx.equals("Y")) {
          strArray = Utility.arrayEntradaSimple("arrDatos", new CreateFromShipmentFurnitureData[0]);
          strArray2 = Utility.arrayEntradaSimple("arrDatos2", CreateFromShipmentFurnitureData
              .selectFromPOSOTrxCombo(this, vars.getLanguage(),
                  Utility.getContext(this, vars, "#User_Client", strWindowId),
                  Utility.getContext(this, vars, "#AccessibleOrgTree", strWindowId), strBPartner));
        } else {
          strArray = Utility.arrayEntradaSimple("arrDatos", CreateFromShipmentFurnitureData
              .selectFromInvoiceCombo(this, vars.getLanguage(),
                  Utility.getContext(this, vars, "#User_Client", strWindowId),
                  Utility.getContext(this, vars, "#AccessibleOrgTree", strWindowId), strBPartner));
          strArray2 = Utility.arrayEntradaSimple(
              "arrDatos2",
              CreateFromShipmentFurnitureData.selectFromPOCombo(this, vars.getLanguage(),
                  Utility.getContext(this, vars, "#User_Client", strWindowId),
                  Utility.getContext(this, vars, "#AccessibleOrgTree", strWindowId), strBPartner));
        }
      } else { // Loading the Combos in the Invoice's CreateFrom
        Invoice invoice = OBDal.getInstance().get(Invoice.class, strKey);
        String strIsTaxIncluded = invoice.getPriceList().isPriceIncludesTax() ? "Y" : "N";

        if (isSOTrx.equals("Y")) {
          strArray = Utility.arrayEntradaSimple("arrDatos", CreateFromInvoiceFurnitureData
              .selectFromShipmentSOTrxCombo(this, vars.getLanguage(),
                  Utility.getContext(this, vars, "#User_Client", strWindowId),
                  Utility.getContext(this, vars, "#AccessibleOrgTree", strWindowId), strBPartner,
                  strIsTaxIncluded));
          strArray2 = Utility.arrayEntradaSimple("arrDatos2", CreateFromInvoiceFurnitureData
              .selectFromPOSOTrxCombo(this, vars.getLanguage(),
                  Utility.getContext(this, vars, "#User_Client", strWindowId),
                  Utility.getContext(this, vars, "#AccessibleOrgTree", strWindowId), strBPartner,
                  strIsTaxIncluded));
        } else {
          strArray = Utility.arrayEntradaSimple("arrDatos", CreateFromInvoiceFurnitureData
              .selectFromShipmentCombo(this, vars.getLanguage(),
                  Utility.getContext(this, vars, "#User_Client", strWindowId),
                  Utility.getContext(this, vars, "#AccessibleOrgTree", strWindowId), strBPartner,
                  strIsTaxIncluded));
          strArray2 = Utility.arrayEntradaSimple("arrDatos2", CreateFromInvoiceFurnitureData
              .selectFromPOCombo(this, vars.getLanguage(),
                  Utility.getContext(this, vars, "#User_Client", strWindowId),
                  Utility.getContext(this, vars, "#AccessibleOrgTree", strWindowId), strBPartner,
                  strIsTaxIncluded));
        }
      }
    }

    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter("array", strArray + "\n" + strArray2);
    response.setContentType("text/html; charset=UTF-8");
    final PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }

  protected OBError saveShipment(VariablesSecureApp vars, String strKey, String strTableId,
      String strProcessId, String strWindowId) throws IOException, ServletException {
    if (log4j.isDebugEnabled())
      log4j.debug("Save: Shipment");
    // final String isSOTrx = Utility.getContext(this, vars, "isSOTrx", strWindowId);
    String isSOTrx = "N";
    if (isSOTrx.equals("Y")) {
      log4j.debug("por aquí entra");
      return saveShipmentSO(vars, strKey, strTableId, strProcessId, strWindowId);
    } else
      return saveShipmentPO(vars, strKey, strTableId, strProcessId, strWindowId);
  }

  protected OBError saveShipmentPO(VariablesSecureApp vars, String strKey, String strTableId,
      String strProcessId, String strWindowId) throws IOException, ServletException {
    if (log4j.isDebugEnabled())
      log4j.debug("Save: Shipment");
    final String strLocatorCommon = vars.getStringParameter("inpmLocatorId");
    final String strType = vars.getRequiredStringParameter("inpType");
    final String strClaves = Utility.stringList(vars.getRequiredInParameter("inpId",
        IsIDFilter.instance));
    final String isSOTrx = Utility.getContext(this, vars, "isSOTrx", strWindowId);
    String strInvoice = "", strPO = "";
    CreateFromShipmentFurnitureData[] data = null;
    OBError myMessage = null;
    Connection conn = null;
    String[] ids = restrictParameter(strClaves);
	    String strmInoutId = "";
			String orderlineid = "";
	String qtydelivered = "";
    try {



	  conn = this.getTransactionConnection();

      strmInoutId = SequenceIdData.getUUID();
      log4j.debug("strmInoutId" + strmInoutId);
      AddOrderOrInvoiceFurnitureData[] lastorder = AddOrderOrInvoiceFurnitureData.selectlastorder2(
          this, strKey);
      String strdoctype = CreateFromShipmentFurnitureData.selectposhipmentdoc(this);
	  String shipmentdocno = Utility.getDocumentNo(conn, this, vars,
            "184", "M_Inout", "", strdoctype, false, true);
      CreateFromShipmentFurnitureData.insertheaderPO(conn, this, strmInoutId,
          lastorder[0].adClientId, lastorder[0].adOrgId, vars.getUser(), "N", shipmentdocno,
          strdoctype, strKey, lastorder[0].dateordered,
          lastorder[0].cBpartnerId, lastorder[0].cBpartnerLocationId, lastorder[0].mWarehouseId,
          vars.getUser());

      log4j.debug("añlsdkjfañsjdf");

	  	String strIds = strClaves.substring(1, strClaves.length() - 1);
    StringTokenizer st = new StringTokenizer(strIds, ",");

     while (st.hasMoreTokens()) {
		 String identifier = st.nextToken().trim();
		  orderlineid=identifier.substring(1, 33);
		  		  log4j.debug("orderlineid: "+ orderlineid);


		  qtydelivered = vars.getStringParameter("inpmovementqty" +orderlineid, "0");
		  log4j.debug("aqewrqewrqwer: "+orderlineid);
		  log4j.debug("qtydelivered: "+qtydelivered);
		  log4j.debug("strType: "+strType);
		   log4j.debug("isSOTrx: "+isSOTrx);



        if (strType.equals("INVOICE")) {
          strInvoice = vars.getStringParameter("inpInvoice");
          if (!isSOTrx.equals("Y"))
            data = CreateFromShipmentFurnitureData.selectFromInvoiceUpdate(conn, this,
                vars.getLanguage(), "('"+orderlineid+"')");
        } else {
          strPO = vars.getStringParameter("inpPurchaseOrder");
          if (isSOTrx.equals("Y"))
            data = CreateFromShipmentFurnitureData.selectFromPOUpdateSOTrx(conn, this,
                vars.getLanguage(), "('"+orderlineid+"')");
          else
            data = CreateFromShipmentFurnitureData.selectFromPOUpdate(conn, this,
                vars.getLanguage(), "('"+orderlineid+"')");
        }
        if (data != null) {
          for (int i = 0; i < data.length; i++) {

            // Obtain the values from the window

            String strLineId = "";

            if (strType.equals("INVOICE")) {
              strLineId = data[i].cInvoicelineId;
            } else {
              strLineId = data[i].cOrderlineId;
            }

            final String strMovementqty = vars.getRequiredNumericParameter("inpmovementqty"
                + orderlineid);
            String strQuantityorder = "";
            String strProductUomId = "";
            String strLocator = vars.getStringParameter("inpmLocatorId" + strLineId);
         //   final String strmAttributesetinstanceId = vars
           //     .getStringParameter("inpmAttributesetinstanceId" + strLineId);
            final String strmAttributesetinstanceId = CreateFromShipmentFurnitureData.selectmattributesetinstanceid(this, orderlineid);
			String strbreakdown = "";
            CreateFromShipmentFurnitureData[] dataUomIdConversion = null;

            if ("".equals(strLocator)) {
              strLocator = strLocatorCommon;
            }

			if ("".equals(strLocator))
			{
				      releaseRollbackConnection(conn);
					  myMessage = new OBError();
					  myMessage.setType("Error");
					  myMessage.setTitle("No ha introducido el hueco de almacén en todas las líneas o en la cabecera");
					  myMessage.setMessage("Repita el proceso introduciendo el hueco de almacén en todas las líneas o en la cabecera");
					  return myMessage;
			}

            if ("".equals(data[i].mProductUomId)) {
              strQuantityorder = "";
              strProductUomId = "";
            } else {
              strQuantityorder = vars.getRequiredStringParameter("inpquantityorder" + strLineId);
              strProductUomId = vars.getRequiredStringParameter("inpmProductUomId" + strLineId);
              dataUomIdConversion = CreateFromShipmentFurnitureData.selectcUomIdConversion(this,
                  strProductUomId);

              if (dataUomIdConversion == null || dataUomIdConversion.length == 0) {
                dataUomIdConversion = CreateFromShipmentFurnitureData.set();
                strbreakdown = "N";
              } else {
                strbreakdown = dataUomIdConversion[0].breakdown;
              }
            }

            //

            String strMultiplyRate = "";
            int stdPrecision = 0;
            if ("Y".equals(strbreakdown)) {
              if (dataUomIdConversion[0].cUomIdConversion.equals("")) {
                releaseRollbackConnection(conn);
                myMessage = Utility.translateError(this, vars, vars.getLanguage(),
                    "ProcessRunError");
                return myMessage;
              }
              final String strInitUOM = dataUomIdConversion[0].cUomIdConversion;
              final String strUOM = data[i].cUomId;
              if (strInitUOM.equals(strUOM))
                strMultiplyRate = "1";
              else
                strMultiplyRate = CreateFromShipmentFurnitureData.multiplyRate(this, strInitUOM,
                    strUOM);
              if (strMultiplyRate.equals(""))
                strMultiplyRate = CreateFromShipmentFurnitureData.divideRate(this, strUOM,
                    strInitUOM);
              if (strMultiplyRate.equals("")) {
                strMultiplyRate = "1";
                releaseRollbackConnection(conn);
                myMessage = Utility.translateError(this, vars, vars.getLanguage(),
                    "ProcessRunError");
                return myMessage;
              }
              stdPrecision = Integer.valueOf(dataUomIdConversion[0].stdprecision).intValue();
              BigDecimal quantity, qty, multiplyRate;

              multiplyRate = new BigDecimal(strMultiplyRate);
              qty = new BigDecimal(strMovementqty);
              boolean qtyIsNegative = false;
              if (qty.compareTo(ZERO) < 0) {
                qtyIsNegative = true;
                qty = qty.negate();
              }
              quantity = qty.multiply(multiplyRate);
              if (quantity.scale() > stdPrecision)
                quantity = quantity.setScale(stdPrecision, BigDecimal.ROUND_HALF_UP);
              while (qty.compareTo(ZERO) > 0) {
                String total = "1";
                BigDecimal conversion;
                if (quantity.compareTo(BigDecimal.ONE) < 0) {
                  total = quantity.toString();
                  conversion = qty;
                  quantity = ZERO;
                  qty = ZERO;
                } else {
                  conversion = multiplyRate;
                  if (conversion.compareTo(qty) > 0) {
                    conversion = qty;
                    qty = ZERO;
                  } else
                    qty = qty.subtract(conversion);
                  quantity = quantity.subtract(BigDecimal.ONE);
                }
                final String strConversion = conversion.toString();
                final String strSequence = SequenceIdData.getUUID();
                try {
                  CreateFromShipmentFurnitureData.insert(conn, this, strSequence, strmInoutId, vars
                      .getClient(), data[i].adOrgId, vars.getUser(), data[i].description,
                      data[i].mProductId, data[i].cUomId, (qtyIsNegative ? "-" + strConversion
                          : strConversion), data[i].cOrderlineId, strLocator,
                      CreateFromShipmentFurnitureData
                          .isInvoiced(conn, this, data[i].cInvoicelineId), (qtyIsNegative ? "-"
                          + total : total), data[i].mProductUomId, strmAttributesetinstanceId,
                      data[i].aAssetId, data[i].cProjectId, data[i].cCostcenterId, data[i].user1Id,
                      data[i].user2Id, data[i].cBpartnerId);

                  if (strType.equals("INVOICE") && !data[i].cInvoicelineId.isEmpty()) {
                    CreateFromShipmentFurnitureData.insertInvoiceAcctDimension(conn, this,
                        strSequence, vars.getClient(), data[i].adOrgId, vars.getUser(),
                        data[i].cInvoicelineId);
                  } else if (!data[i].cOrderlineId.isEmpty()) {
                    CreateFromShipmentFurnitureData.insertAcctDimension(conn, this, strSequence,
                        vars.getClient(), data[i].adOrgId, vars.getUser(), data[i].cOrderlineId);
                  }
                  if (!strInvoice.equals(""))
                    CreateFromShipmentFurnitureData.updateInvoice(conn, this, strSequence,
                        data[i].cInvoicelineId);
                  else
                    CreateFromShipmentFurnitureData.updateInvoiceOrder(conn, this, strSequence,
                        data[i].cOrderlineId);
                } catch (final ServletException ex) {
                  myMessage = Utility.translateError(this, vars, vars.getLanguage(),
                      ex.getMessage());
                  releaseRollbackConnection(conn);
                  return myMessage;
                }
              }
            } else {
              final String strSequence = SequenceIdData.getUUID();
              try {
                CreateFromShipmentFurnitureData.insert(conn, this, strSequence, strmInoutId,
                    vars.getClient(), data[i].adOrgId, vars.getUser(), data[i].description,
                    data[i].mProductId, data[i].cUomId, strMovementqty, data[i].cOrderlineId,
                    strLocator,
                    CreateFromShipmentFurnitureData.isInvoiced(conn, this, data[i].cInvoicelineId),
                    strQuantityorder, strProductUomId, strmAttributesetinstanceId,
                    data[i].aAssetId, data[i].cProjectId, data[i].cCostcenterId, data[i].user1Id,
                    data[i].user2Id, data[i].cBpartnerId);

                if (strType.equals("INVOICE") && !data[i].cInvoicelineId.isEmpty()) {
                  CreateFromShipmentFurnitureData.insertInvoiceAcctDimension(conn, this,
                      strSequence, vars.getClient(), data[i].adOrgId, vars.getUser(),
                      data[i].cInvoicelineId);
                } else if (!data[i].cOrderlineId.isEmpty()) {
                  CreateFromShipmentFurnitureData.insertAcctDimension(conn, this, strSequence,
                      vars.getClient(), data[i].adOrgId, vars.getUser(), data[i].cOrderlineId);
                }
                if (!strInvoice.equals("")) {
                  String strInOutLineId = CreateFromShipmentFurnitureData.selectInvoiceInOut(conn,
                      this, data[i].cInvoicelineId);
                  if (strInOutLineId.isEmpty())
                    CreateFromShipmentFurnitureData.updateInvoice(conn, this, strSequence,
                        data[i].cInvoicelineId);
                  else {
                    CreateFromShipmentFurnitureData.insertMatchInv(conn, this, vars.getUser(),
                        data[i].cInvoicelineId, strSequence, data[i].cInvoiceId);
                  }
                } else
                  CreateFromShipmentFurnitureData.updateInvoiceOrder(conn, this, strSequence,
                      data[i].cOrderlineId);
              } catch (final ServletException ex) {
                myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                releaseRollbackConnection(conn);
                return myMessage;
              }
            }
          }
        }

        if (!strPO.equals("")) {
          try {
            final int total = CreateFromShipmentFurnitureData.deleteC_Order_ID(conn, this, strKey,
                strPO);
            if (total == 0)
              CreateFromShipmentFurnitureData.updateC_Order_ID(conn, this, strPO, strKey);
          } catch (final ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            releaseRollbackConnection(conn);
            return myMessage;
          }
        }
        if (!strInvoice.equals("")) {
          try {
            final int total = CreateFromShipmentFurnitureData.deleteC_Invoice_ID(conn, this,
                strKey, strInvoice);
            if (total == 0)
              CreateFromShipmentFurnitureData.updateC_Invoice_ID(conn, this, strInvoice, strKey);
          } catch (final ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            releaseRollbackConnection(conn);
            return myMessage;
          }
        }
      }

      releaseCommitConnection(conn);
      if (log4j.isDebugEnabled())
        log4j.debug("Save commit");
      myMessage = new OBError();
      myMessage.setType("Success");
      myMessage.setTitle("");
      myMessage.setMessage(Utility.messageBD(this, "Success", vars.getLanguage()));
    } catch (final Exception e) {
      try {
        releaseRollbackConnection(conn);
      } catch (final Exception ignored) {
      }
      e.printStackTrace();
      log4j.warn("Rollback in transaction");
      myMessage = Utility.translateError(this, vars, vars.getLanguage(), "ProcessRunError");
    }

   ShipmentInOut goods = (ShipmentInOut) OBDal.getInstance().getProxy(ShipmentInOut.ENTITY_NAME,
        strmInoutId);
    goods.setDocumentAction("CO");
    OBDal.getInstance().save(goods);
    OBDal.getInstance().flush();
    Process process = null;
    try {
      OBContext.setAdminMode(true);
      process = (Process) OBDal.getInstance().getProxy(Process.ENTITY_NAME, M_Inout_Post_ID);
    } finally {
      OBContext.restorePreviousMode();
    }

    Map<String, String> parameters = null;

    final ProcessInstance pinstance = CallProcess.getInstance().call(process, strmInoutId,
        parameters);
    OBDal.getInstance().getSession().refresh(goods);
    goods.setProcessGoodsJava(goods.getDocumentAction());
    OBDal.getInstance().save(goods);
    OBDal.getInstance().flush();
    OBDal.getInstance().commitAndClose();

    final PInstanceProcessData[] pinstanceData = PInstanceProcessData.select(this,
        pinstance.getId());
    myMessage = Utility.getProcessInstanceMessage(this, vars, pinstanceData);
    return myMessage;


  }

  protected OBError saveShipmentSO(VariablesSecureApp vars, String strKey, String strTableId,
      String strProcessId, String strWindowId) throws IOException, ServletException {
    if (log4j.isDebugEnabled())
      log4j.debug("Save: Shipment");
    log4j.debug("por aquí entra");
    String strLocator = "";
	String orderlineid = "";
	String qtydelivered = "";
    final String strType = vars.getRequiredStringParameter("inpType");
    final String strClaves = Utility.stringList(vars.getRequiredInParameter("inpId",
        IsIDFilter.instance));
	log4j.debug("strClaves: "+strClaves);



    final String isSOTrx = Utility.getContext(this, vars, "isSOTrx", strWindowId);
    String strInvoice = "", strPO = "";
    CreateFromShipmentFurnitureData[] data = null;
    OBError myMessage = null;
    Connection conn = null;
    String[] ids = restrictParameter(strClaves);
    String strmInoutId = "";
    try {
      conn = this.getTransactionConnection();

      strmInoutId = SequenceIdData.getUUID();
      log4j.debug("strmInoutId" + strmInoutId);
      AddOrderOrInvoiceFurnitureData[] lastorder = AddOrderOrInvoiceFurnitureData.selectlastorder2(
          this, strKey);
      String strdoctype = CreateFromShipmentFurnitureData.selectsoshipmentdoc(this);
	  String shipmentdocno = Utility.getDocumentNo(conn, this, vars,
            "169", "M_Inout", "", strdoctype, false, true);
      CreateFromShipmentFurnitureData.insertheader(conn, this, strmInoutId,
          lastorder[0].adClientId, lastorder[0].adOrgId, vars.getUser(), "Y", shipmentdocno,
          strdoctype, strKey, lastorder[0].dateordered,
          lastorder[0].cBpartnerId, lastorder[0].cBpartnerLocationId, lastorder[0].mWarehouseId,
          vars.getUser());

      log4j.debug("añlsdkjfañsjdf");

	  	String strIds = strClaves.substring(1, strClaves.length() - 1);
    StringTokenizer st = new StringTokenizer(strIds, ",");

     while (st.hasMoreTokens()) {
		 String identifier = st.nextToken().trim();
		  orderlineid=identifier.substring(1, 33);
		  		  log4j.debug("orderlineid: "+ orderlineid);

		  strLocator=identifier.substring(33, 65);
		  log4j.debug("strLocator: "+strLocator);
		  qtydelivered = vars.getStringParameter("inpQty" +identifier.substring(1, identifier.length() - 1), "0");
		  log4j.debug("aqewrqewrqwer: "+identifier.substring(1, identifier.length() - 1));
		  log4j.debug("qtydelivered: "+qtydelivered);
		  log4j.debug("strType: "+strType);
		   log4j.debug("isSOTrx: "+isSOTrx);
        if (strType.equals("INVOICE")) {
          strInvoice = vars.getStringParameter("inpInvoice");
          if (isSOTrx.equals("Y"))
            data = CreateFromShipmentFurnitureData.selectFromInvoiceTrxUpdate(conn, this,
                vars.getLanguage(), "('"+identifier.substring(1, 33)+"')");
          else
            data = CreateFromShipmentFurnitureData.selectFromInvoiceUpdate(conn, this,
                vars.getLanguage(), "('"+identifier.substring(1, 33)+"')");
        } else {
          strPO = vars.getStringParameter("inpPurchaseOrder");
          if (isSOTrx.equals("Y"))
            data = CreateFromShipmentFurnitureData.selectFromPOUpdateSOTrx(conn, this,
                vars.getLanguage(), "('"+identifier.substring(1, 33)+"')");
          else
            data = CreateFromShipmentFurnitureData.selectFromPOUpdate(conn, this,
                vars.getLanguage(), "('"+identifier.substring(1, 33)+"')");
        }
		log4j.debug("data.length: "+data.length);
        if (data != null) {
          for (int i = 0; i < data.length; i++) {
            String strMultiplyRate = "";
            int stdPrecision = 0;
            if (data[i].breakdown.equals("Y")) {
              if (data[i].cUomIdConversion.equals("")) {
                releaseRollbackConnection(conn);
                myMessage = Utility.translateError(this, vars, vars.getLanguage(),
                    "ProcessRunError");
                return myMessage;
              }
              final String strInitUOM = data[i].cUomIdConversion;
              final String strUOM = data[i].cUomId;
              if (strInitUOM.equals(strUOM))
                strMultiplyRate = "1";
              else
                strMultiplyRate = CreateFromShipmentFurnitureData.multiplyRate(this, strInitUOM,
                    strUOM);
              if (strMultiplyRate.equals(""))
                strMultiplyRate = CreateFromShipmentFurnitureData.divideRate(this, strUOM,
                    strInitUOM);
              if (strMultiplyRate.equals("")) {
                strMultiplyRate = "1";
                releaseRollbackConnection(conn);
                myMessage = Utility.translateError(this, vars, vars.getLanguage(),
                    "ProcessRunError");
                return myMessage;
              }
              stdPrecision = Integer.valueOf(data[i].stdprecision).intValue();
              BigDecimal quantity, qty, multiplyRate;

              multiplyRate = new BigDecimal(strMultiplyRate);
              qty = new BigDecimal(data[i].id);
              boolean qtyIsNegative = false;
              if (qty.compareTo(ZERO) < 0) {
                qtyIsNegative = true;
                qty = qty.negate();
              }
              quantity = qty.multiply(multiplyRate);
              if (quantity.scale() > stdPrecision)
                quantity = quantity.setScale(stdPrecision, BigDecimal.ROUND_HALF_UP);
              while (qty.compareTo(ZERO) > 0) {
                String total = "1";
                BigDecimal conversion;
                if (quantity.compareTo(BigDecimal.ONE) < 0) {
                  total = quantity.toString();
                  conversion = qty;
                  quantity = ZERO;
                  qty = ZERO;
                } else {
                  conversion = multiplyRate;
                  if (conversion.compareTo(qty) > 0) {
                    conversion = qty;
                    qty = ZERO;
                  } else
                    qty = qty.subtract(conversion);
                  quantity = quantity.subtract(BigDecimal.ONE);
                }
                final String strConversion = conversion.toString();
                final String strSequence = SequenceIdData.getUUID();
                try {
                  CreateFromShipmentFurnitureData.insert(conn, this, strSequence, strmInoutId, vars
                      .getClient(), data[i].adOrgId, vars.getUser(), data[i].description,
                      data[i].mProductId, data[i].cUomId, qtydelivered, data[i].cOrderlineId, strLocator,
                      CreateFromShipmentFurnitureData
                          .isInvoiced(conn, this, data[i].cInvoicelineId), (qtyIsNegative ? "-"
                          + total : total), data[i].mProductUomId, data[i].mAttributesetinstanceId,
                      data[i].aAssetId, data[i].cProjectId, data[i].cCostcenterId, data[i].user1Id,
                      data[i].user2Id, data[i].cBpartnerId);

                  if (strType.equals("INVOICE") && !data[i].cInvoicelineId.isEmpty()) {
                    CreateFromShipmentFurnitureData.insertInvoiceAcctDimension(conn, this,
                        strSequence, vars.getClient(), data[i].adOrgId, vars.getUser(),
                        data[i].cInvoicelineId);
                  } else if (!data[i].cOrderlineId.isEmpty()) {
                    CreateFromShipmentFurnitureData.insertAcctDimension(conn, this, strSequence,
                        vars.getClient(), data[i].adOrgId, vars.getUser(), data[i].cOrderlineId);
                  }

                  if (!strInvoice.equals(""))
                    CreateFromShipmentFurnitureData.updateInvoice(conn, this, strSequence,
                        data[i].cInvoicelineId);
                  else
                    CreateFromShipmentFurnitureData.updateInvoiceOrder(conn, this, strSequence,
                        data[i].cOrderlineId);
                } catch (final ServletException ex) {
                  myMessage = Utility.translateError(this, vars, vars.getLanguage(),
                      ex.getMessage());
                  releaseRollbackConnection(conn);
                  return myMessage;
                }
              }
            } else {
              final String strSequence = SequenceIdData.getUUID();
              try {
                CreateFromShipmentFurnitureData.insert(conn, this, strSequence, strmInoutId,
                    vars.getClient(), data[i].adOrgId, vars.getUser(), data[i].description,
                    data[i].mProductId, data[i].cUomId, qtydelivered, data[i].cOrderlineId,
                    strLocator,
                    CreateFromShipmentFurnitureData.isInvoiced(conn, this, data[i].cInvoicelineId),
                    data[i].quantityorder, data[i].mProductUomId, data[i].mAttributesetinstanceId,
                    data[i].aAssetId, data[i].cProjectId, data[i].cCostcenterId, data[i].user1Id,
                    data[i].user2Id, data[i].cBpartnerId);

                if (strType.equals("INVOICE") && !data[i].cInvoicelineId.isEmpty()) {
                  CreateFromShipmentFurnitureData.insertInvoiceAcctDimension(conn, this,
                      strSequence, vars.getClient(), data[i].adOrgId, vars.getUser(),
                      data[i].cInvoicelineId);
                } else if (!data[i].cOrderlineId.isEmpty()) {
                  CreateFromShipmentFurnitureData.insertAcctDimension(conn, this, strSequence,
                      vars.getClient(), data[i].adOrgId, vars.getUser(), data[i].cOrderlineId);
                }

                if (!strInvoice.equals(""))
                  CreateFromShipmentFurnitureData.updateInvoice(conn, this, strSequence,
                      data[i].cInvoicelineId);
                else
                  CreateFromShipmentFurnitureData.updateInvoiceOrder(conn, this, strSequence,
                      data[i].cOrderlineId);
              } catch (final ServletException ex) {
                myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                releaseRollbackConnection(conn);
                return myMessage;
              }
            }
          }
        }

        if (!strPO.equals("")) {
          try {
            final int total = CreateFromShipmentFurnitureData.deleteC_Order_ID(conn, this, strKey,
                strPO);
            if (total == 0)
              CreateFromShipmentFurnitureData.updateC_Order_ID(conn, this, strPO, strKey);
          } catch (final ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            releaseRollbackConnection(conn);
            return myMessage;
          }
        }
        if (!strInvoice.equals("")) {
          try {
            final int total = CreateFromShipmentFurnitureData.deleteC_Invoice_ID(conn, this,
                strKey, strInvoice);
            if (total == 0)
              CreateFromShipmentFurnitureData.updateC_Invoice_ID(conn, this, strInvoice, strKey);
          } catch (final ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            releaseRollbackConnection(conn);
            return myMessage;
          }
        }

      }
      releaseCommitConnection(conn);
      if (log4j.isDebugEnabled())
        log4j.debug("Save commit");
      myMessage = new OBError();
      myMessage.setType("Success");
      myMessage.setTitle("");
      myMessage.setMessage(Utility.messageBD(this, "Success", vars.getLanguage()));
    } catch (final Exception e) {
      try {
        releaseRollbackConnection(conn);
      } catch (final Exception ignored) {
      }
      e.printStackTrace();
      log4j.warn("Rollback in transaction");
      myMessage = Utility.translateError(this, vars, vars.getLanguage(), "ProcessRunError");
    }
    ShipmentInOut goods = (ShipmentInOut) OBDal.getInstance().getProxy(ShipmentInOut.ENTITY_NAME,
        strmInoutId);
    goods.setDocumentAction("CO");
    OBDal.getInstance().save(goods);
    OBDal.getInstance().flush();
    Process process = null;
    try {
      OBContext.setAdminMode(true);
      process = (Process) OBDal.getInstance().getProxy(Process.ENTITY_NAME, M_Inout_Post_ID);
    } finally {
      OBContext.restorePreviousMode();
    }

    Map<String, String> parameters = null;

    final ProcessInstance pinstance = CallProcess.getInstance().call(process, strmInoutId,
        parameters);
    OBDal.getInstance().getSession().refresh(goods);
    goods.setProcessGoodsJava(goods.getDocumentAction());
    OBDal.getInstance().save(goods);
    OBDal.getInstance().flush();
    OBDal.getInstance().commitAndClose();

    final PInstanceProcessData[] pinstanceData = PInstanceProcessData.select(this,
        pinstance.getId());
    myMessage = Utility.getProcessInstanceMessage(this, vars, pinstanceData);
    return myMessage;
  }

  private String[] restrictParameter(String strIds) {
    String[] ids = null;
    if (strIds == null || ("").equals(strIds)) {
      return new String[0];
    }
    strIds = strIds.substring(1, strIds.length() - 1);
    StringTokenizer st = new StringTokenizer(strIds, ",");
    int noOfRecords = 1;
    int tokenCount = st.countTokens();
    final double totalRecords = 900.0;
    int strArrayCount = tokenCount <= totalRecords ? 0 : (int) Math.ceil(tokenCount / totalRecords);
    if (strArrayCount != 0) {
      ids = new String[strArrayCount];
    } else {
      ids = new String[1];
      ids[0] = "(" + strIds + ")";
    }

    int count = 1;
    String tempIds = "";
    if (strArrayCount != 0) {
      while (st.hasMoreTokens()) {
        tempIds = tempIds + st.nextToken();
        if ((noOfRecords % totalRecords) != 0 && st.hasMoreTokens()) {
          tempIds = tempIds + ",";
        }
        if ((noOfRecords % totalRecords) == 0 || (strArrayCount == count && !st.hasMoreTokens())) {
          ids[count - 1] = "(" + tempIds + ")";
          tempIds = "";
          count++;
        }
        noOfRecords++;
      }

    }
    return ids;

  }

  @Override
  public String getServletInfo() {
    return "Servlet that presents the button of CreateFrom";
  } // end of getServletInfo() method
}
